<template>
    <div class="role-management">
      <!-- 头部区域 -->
      <div class="header-container">
        <div class="left">
          <i class="el-icon-user-solid"></i>
          <span>角色管理</span>
        </div>
        <div class="right">
          <el-button type="primary" @click="handleAddRole">
            <i class="el-icon-plus"></i> 新增角色
          </el-button>
        </div>
      </div>
  
      <!-- 主体内容区 -->
      <div class="content-container">
        <el-card>
          <el-table
            :data="roles"
            border
            style="width: 100%"
            v-loading="loading">
            <el-table-column prop="roleName" label="角色名称" width="180"/>
            <el-table-column prop="roleCode" label="角色编码" width="180"/>
            <el-table-column prop="description" label="描述"/>
            <el-table-column prop="createdAt" label="创建时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleAssignPermission(scope.row)">
                  分配权限
                </el-button>
                <el-button
                  size="mini"
                  type="success"
                  @click="handleEditRole(scope.row)">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteRole(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
  
      <!-- 角色表单对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        :modal="true"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
        custom-class="feedback-dialog"
        width="500px">
        <el-form
          :model="roleForm"
          :rules="rules"
          ref="roleForm"
          label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName"/>
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="roleForm.roleCode"/>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              v-model="roleForm.description"
              :rows="3"/>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitRole">确 定</el-button>
        </div>
      </el-dialog>
  
      <!-- 分配权限对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="permissionDialogVisible"
        :modal="true"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :append-to-body="true"
        :destroy-on-close="true"
        custom-class="feedback-dialog"
        width="600px">
        <el-tree
          ref="permissionTree"
          :data="permissionTree"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedPermissions"
          :default-expand-all="true"
          class="permission-tree">
        </el-tree>
        <div slot="footer">
          <el-button @click="closePermissionDialog">取 消</el-button>
          <el-button type="primary" @click="submitPermissions">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
  
  export default {
    name: 'RoleManagement',
    data() {
      return {
        roles: [],
        loading: false,
        dialogVisible: false,
        dialogTitle: '新增角色',
        permissionDialogVisible: false,
        currentRole: null,
        roleForm: {
          roleName: '',
          roleCode: '',
          description: ''
        },
        rules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          roleCode: [
            { required: true, message: '请输入角色编码', trigger: 'blur' }
          ]
        },
        permissionTree: [],
        selectedPermissions: [],
        defaultProps: {
          children: 'children',
          label: 'namezh'
        }
      }
    },
    created() {
      this.fetchRoles()
    },
    methods: {
      formatDate(date) {
        if (!date) return '';
        
        if (typeof date === 'string') {
          date = new Date(date);
        }
        
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      async fetchRoles() {
        try {
          this.loading = true
          const res = await axios.get('/api/system/role/list')
          this.roles = res.data.data
        } catch (error) {
          this.$message.error('获取角色列表失败')
        } finally {
          this.loading = false
        }
      },
      handleAddRole() {
        this.dialogTitle = '新增角色'
        this.roleForm = {
          roleName: '',
          roleCode: '',
          description: ''
        }
        this.dialogVisible = true
      },
      handleEditRole(role) {
        this.dialogTitle = '编辑角色'
        this.roleForm = { ...role }
        this.dialogVisible = true
      },
      async handleDeleteRole(role) {
        try {
          await this.$confirm('确认删除该角色吗？', '提示', {
            type: 'warning'
          })
          await axios.delete(`/api/system/role/${role.id}`)
          this.$message.success('删除成功')
          this.fetchRoles()
        } catch (error) {
          if (error !== 'cancel') {
            this.$message.error('删除失败')
          }
        }
      },
      async handleAssignPermission(role) {
        // 先获取数据
        try {
          const [treeRes, selectedRes] = await Promise.all([
            axios.get('/api/system/permission/tree'),
            axios.get(`/api/system/permission/role/${role.id}`)
          ]);
          
          this.permissionTree = treeRes.data.data;
          this.selectedPermissions = selectedRes.data.data.map(p => p.id);
          
          // 然后再显示对话框
          this.$nextTick(() => {
            this.currentRole = role;
            this.permissionDialogVisible = true;
            // 强制更新树的选中状态
            if (this.$refs.permissionTree) {
              this.$refs.permissionTree.setCheckedKeys(this.selectedPermissions);
            }
          });
        } catch (error) {
          this.$message.error('获取权限数据失败');
        }
      },
      closePermissionDialog() {
        this.permissionDialogVisible = false;
        this.selectedPermissions = [];
        this.currentRole = null;
      },
      async submitPermissions() {
        if (!this.currentRole) return;
        
        try {
          const checkedKeys = this.$refs.permissionTree.getCheckedKeys();
          await axios.post(`/api/system/permission/role/${this.currentRole.id}`, checkedKeys);
          this.$message.success('权限分配成功');
          this.closePermissionDialog();
        } catch (error) {
          this.$message.error('权限分配失败');
        }
      },
      handleClose() {
        document.body.style.overflow = 'auto';
        this.dialogVisible = false;
        this.permissionDialogVisible = false;
      },
      async submitRole() {
        try {
          // 表单验证
          await this.$refs.roleForm.validate();
          
          if (this.roleForm.id) {
            // 编辑角色
            await axios.put(`/api/system/role/${this.roleForm.id}`, this.roleForm);
            this.$message.success('角色更新成功');
          } else {
            // 新增角色
            console.log('提交的角色数据：', this.roleForm); // 调试日志
            const response = await axios.post('/api/system/role/create', this.roleForm);
            console.log('服务器响应：', response.data); // 调试日志
            this.$message.success('角色创建成功');
          }
          
          // 关闭弹窗并刷新列表
          this.dialogVisible = false;
          this.fetchRoles();
        } catch (error) {
          console.error('提交角色失败：', error); // 调试日志
          this.$message.error(error.response?.data?.message || '操作失败');
        }
      }
    }
  }
  </script>
  
  <style>
/* 注意：这里不使用 scoped，以便样式能够作用到弹窗 */
.feedback-dialog {
  background: #fff !important;
}

.feedback-dialog .el-dialog__header {
  background: #1a237e;
  padding: 20px;
  border-radius: 8px 8px 0 0;
  margin-right: 0;
}

.feedback-dialog .el-dialog__title {
  color: white;
  font-size: 18px;
  line-height: 24px;
}

.feedback-dialog .el-dialog__headerbtn {
  top: 15px;
}

.feedback-dialog .el-dialog__headerbtn .el-dialog__close {
  color: white;
}

.feedback-dialog .el-dialog__body {
  padding: 30px 20px;
  background: #fff;
}

.feedback-dialog .el-dialog__footer {
  padding: 15px 20px;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

/* 遮罩层样式 */
.v-modal {
  opacity: 0.5 !important;
}
</style>

<style scoped>
.role-management {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 16px;
}

/* 页面标题样式 - 修改为匹配实际使用的类名 */
.header-container {
  background: #1a237e;
  color: white;
  padding: 16px 24px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.header-container .left {
  display: flex;
  align-items: center;
  font-size: 18px;
}

.header-container .left i {
  font-size: 24px;
  margin-right: 8px;
}

/* 内容区域样式 */
.content-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 16px;
}

/* 表格样式 */
.role-management .el-table th {
  background-color: #1a237e !important;
  color: white !important;
  font-weight: 500;
  padding: 12px 0;
}

.role-management .el-table td {
  padding: 12px 0;
}

/* 按钮样式 */
.role-management .el-button--primary {
  background-color: #1a237e;
  border-color: #1a237e;
}

.role-management .el-button--primary:hover,
.role-management .el-button--primary:focus {
  background-color: #283593;
  border-color: #283593;
}

.role-management .el-button--success {
  background-color: #4caf50;
  border-color: #4caf50;
}

.role-management .el-button--danger {
  background-color: #f44336;
  border-color: #f44336;
}

.role-management .el-button--mini {
  border-radius: 4px;
}

/* 卡片样式 */
.role-management .el-card {
  border: none;
  margin-bottom: 0;
}

/* 权限树样式 */
.permission-tree {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .header-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-container .right {
    margin-top: 10px;
    width: 100%;
  }
  
  .header-container .right .el-button {
    width: 100%;
  }
}
</style>